package cn.vastbase.jdbc.advanced.batch;

import org.junit.Test;

import java.sql.*;

public class BatchTestCase {

    /* 定义连接对象 */
    static Connection conn = null;
    static String cname = "org.postgresql.Driver";
    static String url = "jdbc:postgresql://172.16.55.175:6666/zxsdb?reWriteBatchedInserts=true&batchMode=off";
    static String username = "zxs";
    static String passwd = "Vastdata#0730";
    /* 定义 SQL 语句执行对象 */
    static Statement stmt = null;
    static PreparedStatement pstmt = null;
    /* 定义结果集对象 */
    static ResultSet rs = null;

    public Connection conn() {
        try {
            Class.forName(cname);
            return conn = DriverManager.getConnection(url, username, passwd);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        return null;

    }

    public void close() {
        try {
            /* 关闭结果集对象 */
            if (rs != null)
                rs.close();
        } catch (SQLException e) {
            System.out.println("[FAIL] close resultSet fail." + e.getMessage());
        }
        try {
            /* 关闭语句对象 */
            if (stmt != null)
                stmt.close();
        } catch (SQLException e) {
            System.out.println("[FAIL] close statement fail." + e.getMessage());
        }
        try {
            /* 关闭语句对象 */
            if (pstmt != null)
                pstmt.close();
        } catch (SQLException e) {
            System.out.println("[FAIL] close statement fail." + e.getMessage());
        }
        try {
            /* 关闭连接 */
            conn.close();
        } catch (SQLException e) {
            System.out.println("[FAIL] close connection fail." + e.getMessage());
        }
    }

    /**
     * @Title: 批量插入数据
     * @Description: 发送到数据库的SQL：insert into users (id, username) values(?,?),(?,?),(?,?)
     * @throws SQLException
     */
    @Test
    public void testBatchs() throws SQLException {

        if (conn() == null)
            return;
        try {
            pstmt = conn.prepareStatement("insert into users (id, username) values(?,?)");
            for (int i = 0; i < 5; i++) {
                pstmt.setInt(1, i);
                pstmt.setString(2, "ii" + i);
                pstmt.addBatch();
            }
            pstmt.executeBatch();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close();
        }
    }
}
